package com.whpu.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whpu.common.constant.WareConstant;
import com.whpu.common.utils.PageUtils;
import com.whpu.common.utils.Query;
import com.whpu.common.utils.RRException;
import com.whpu.mall.ware.dao.PurchaseDao;
import com.whpu.mall.ware.entity.PurchaseDetailEntity;
import com.whpu.mall.ware.entity.PurchaseEntity;
import com.whpu.mall.ware.service.PurchaseDetailService;
import com.whpu.mall.ware.service.PurchaseService;
import com.whpu.mall.ware.service.WareSkuService;
import com.whpu.mall.ware.vo.MergeVo;
import com.whpu.mall.ware.vo.PurchaseDoneVo;
import com.whpu.mall.ware.vo.PurchaseItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取所有未被分配的采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils purchaseUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status",0).or()
                .eq("status",1)
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购单
     * @param mergeVo
     */
    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){  //为空则新建一个合并采购单

            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        PurchaseEntity purchaseEntity = baseMapper.selectById(purchaseId);
        //当采购单状态为0或者1时才可合并
        if(purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode() ){
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item);
                detailEntity.setPurchaseId(finalPurchaseId);
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            //修改合并单
            detailService.updateBatchById(collect);
        }else {
            throw new RRException("采购单状态有误,无法合并!");
        }


    }

    /**
     * 领取采购单
     * @param ids
     */
    @Override
    public void receivedPurchase(List<Long> ids) {
        // 查询未分配或新建的采购单
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.baseMapper.selectById(id);
            return purchaseEntity;
        }).filter(item -> {   //返回未分配或新建的采购单
            return (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());

        //修改采购单
        this.updateBatchById(purchaseEntityList);

        //改变采购项状态
        purchaseEntityList.forEach(item -> {
            List<PurchaseDetailEntity> purchases = detailService.getBypurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntityList = purchases.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            detailService.updateBatchById(detailEntityList);
        });
    }

    /**
     * 条件查询采购单
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(w->{
               w.like("assignee_name",key).or().like("phone",key);
            });
        }
        if (StringUtils.isNotEmpty(status)){
            wrapper.eq("status",status);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 完成采购单
     * @param doneVo
     */
    @Override
    @Transactional
    public void purchaseDone(PurchaseDoneVo doneVo) {

        //1.改变采购项状态(成功/失败)
        List<PurchaseItemVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> targets = new ArrayList<>();
        boolean flag = true;

        for (PurchaseItemVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //采购失败
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else {
                //采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //将采购单入库,添加库存
                //添加库存,当前商品(sku_id)给哪个仓库(ware_id)添加多少库存(stock)
                PurchaseDetailEntity purchaseDetail = detailService.getById(item.getItemId());
                wareSkuService.addStock(purchaseDetail.getSkuId()
                                        ,purchaseDetail.getWareId()
                                        ,purchaseDetail.getSkuNum());

            }
            detailEntity.setId(item.getItemId());
            targets.add(detailEntity);
        }
        detailService.updateBatchById(targets);

        //2.改变采购单状态
        Long id = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        //采购项全部成功则采购单成功,否则采购单失败
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                :WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);

    }

}
